package com.rizzo.analytics.services.web.controller.v1;

import com.mangofactory.swagger.annotations.ApiModel;
import com.rizzo.analytics.domain.account.Account;
import com.rizzo.analytics.domain.application.Applications;
import com.rizzo.infrastructure.dark.DarkLaunch;
import com.rizzo.infrastructure.performance.Monitor;
import com.rizzo.infrastructure.quota.Quota;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiError;
import com.wordnik.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller("applicationController")
@RequestMapping(value = "/application", produces = "application/json")
@Api(value = "/application", description = "Operations about available applications for a user.")
public class ApplicationController extends RizzoController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationController.class);

    @Monitor(userBound = true)
    @PreAuthorize("hasRole('" + Account.ROLE_USER + "')")
    @Quota(maxCalls = 10, expireSeconds = 30)
    @DarkLaunch(name = "get-applications")
    @RequestMapping(method = RequestMethod.GET, produces = "application/json")
    @ApiOperation(value = "List all possible applications for a user",
            notes = "Returns all the available full names of the applications for a certain user. " +
                    "The result of this method must be provided as a param for the other resource calls. " +
                    "This endpoint can only be called when logged in! " +
                    "If no applications are shown in the response this means you first have to save some data " +
                    "(see POST methods of /performance, /error and /quota).",
            responseClass = "com.rizzo.analytics.domain.application.Applications", tags = "application")
    @com.wordnik.swagger.annotations.ApiErrors(
            {@ApiError(code = 404, reason = "Quota exceeded"),
                    @ApiError(code = 404, reason = "Not available")}
    )
    @ApiModel(type = Applications.class)
    public Applications getApplications() {
        final String user = getUsernameFromContext();
        LOGGER.debug("Asking for all the applications of [user : '{}']", user);
        return analyticsDelegator.getApplications(user);
    }

}
